package com.location.LocationGPS;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Locationtest2Activity extends Activity {
    /** Called when the activity is first created. */
	public LocationManager lm;
	public Location currentLocation = null;
	private LocationListener locationListener;
	public static final int OUT_OF_SERVICE = 0;
	public static final int TEMPORARILY_UNAVAILABLE = 1;
	public static final int AVAILABLE = 2;
	public TextView outlat;
	public TextView outlong;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        outlat = (TextView) findViewById(R.id.outlat);
        outlong = (TextView) findViewById(R.id.outlong);
        
        locationListener = new MyLocationListener();
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        // busca el boton y le asigna un listener
        
        Button btsearch = (Button) findViewById(R.id.buscar);
		btsearch.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mostrar();
			}
			
		});
        
   
    }
    
    private void setCurrentLocation(Location loc) {
    	currentLocation = loc;
    }
    private void mostrar()
    {
    	// paro de escuchar con removeUpdates
    	lm.removeUpdates(locationListener);
    	//Pregunto si no es null e imprimo los valores
    	if (currentLocation!=null) {
    		outlat.setText("Latitude: " + currentLocation.getLatitude());
    		outlong.setText("Longitude: " + currentLocation.getLongitude());
    	}
    }
    private final class MyLocationListener implements LocationListener {
  
        public void onLocationChanged(Location loc) {
            // called when the listener is notified with a location update from the GPS
        	
        	  if (loc != null) 
        	  {
        		  setCurrentLocation(loc);
        		  outlong.setText(loc.toString());
        	  }
        	
        }
 
        
        public void onProviderDisabled(String provider) {
           // called when the GPS provider is turned off (user turning off the GPS on the phone)
        }
 
       
        public void onProviderEnabled(String provider) {
           // called when the GPS provider is turned on (user turning on the GPS on the phone)
        }
 
        
        public void onStatusChanged(String provider, int status, Bundle extras) {
           // called when the status of the GPS provider changes
        }
}
}